import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Roles } from './entities/role.entity';
import { Repository, In } from 'typeorm';
import { MenuService } from '../menu/menu.service';
import { User } from '../user/entities/user.entity';

@Injectable()
export class RolesService {
  constructor(
    @InjectRepository(Roles)
    private readonly rolesRepository: Repository<Roles>,

    @Inject(forwardRef(() => MenuService))
    private menuService: MenuService,

    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
  async create(createRoleDto: Partial<Roles>) {
    const tempRole = this.rolesRepository.create(createRoleDto);
    if (createRoleDto.menus.length) {
      tempRole.menus = await this.menuService.findById(createRoleDto.menus);
    }
    return await this.rolesRepository.save(tempRole);
  }
  // 用户新增角色
  async addUser(body) {
    const roleTemp = await this.findOne(body.role);
    if (body.user.length) {
      roleTemp.users = await this.userRepository.find({
        where: { id: In(body.user) },
      });
    }
    return this.rolesRepository.save(roleTemp);
  }
  async findAll(query) {
    const { pageSize = 10, pageNum = 1, ...params } = query;
    const role = this.rolesRepository
      .createQueryBuilder('roles')
      .leftJoinAndSelect('roles.menus', 'menus');
    for (const key in params) {
      if (params[key]) {
        role.where(`roles.${key} LIKE :${key}`, { [key]: `%${params[key]}%` });
      }
    }
    const [rows, total] = await role
      .skip((pageNum - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    return { rows, total };
  }

  async findOne(id) {
    return await this.rolesRepository.findOne({ where: { id } });
  }

  async findByIds(ids) {
    return await this.rolesRepository.find({ where: { id: In(ids) } });
  }
  //
  async update(id: any, updateRoleDto: Partial<Roles>) {
    const role = await this.findOne(id);
    const roleTemp = this.rolesRepository.merge(role, updateRoleDto);
    if (updateRoleDto.menus?.length) {
      roleTemp.menus = await this.menuService.findById(updateRoleDto.menus);
    }
    return this.rolesRepository.save(roleTemp);
  }

  remove(id: number) {
    return this.rolesRepository.delete(id);
  }
}
